package priv.lhy.ecm.collectorProducer.nettyClient;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import priv.lhy.common.utils.StringUtil;
import priv.lhy.ecm.collectorProducer.aftertreatment.record.IDispose;
import priv.lhy.ecm.collectorProducer.constants.ExceptionType;
import priv.lhy.ecm.collectorProducer.constants.ReuploadType;

/**
 * @author: lihy
 * date: 2019/6/18 14:36
 * description:
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class ClientHandler extends SimpleChannelInboundHandler<String> {


    @Autowired
    private ApplicationContext applicationContext;

    @Value("${upload.keepRecord.type}")
    private int keepRecordType;

    //private IDispose dispose;

    @Bean
    private IDispose getDispose(){
        return (IDispose) applicationContext.getBean("disposeBy"
                + StringUtil.firstCharUpperCase(ReuploadType.values()[keepRecordType].name().toLowerCase()));
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        /*dispose = (IDispose) applicationContext.getBean("disposeBy"
                + StringUtil.firstCharUpperCase(ReuploadType.values()[keepRecordType].name().toLowerCase()));*/
        log.info("返回信息：" + msg);
        if("ok".equals(msg)){
            log.info("上传成功");
        }else{
            //服务器返回错误信息
            saveRecords(ctx, ExceptionType.RETURN_ERROR);
        }
        ctx.channel().close();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        saveRecords(ctx, ExceptionType.CONNECT_EXCEPTION);
    }

    private void saveRecords(ChannelHandlerContext ctx, ExceptionType type){
        AttributeKey<String> attKey = AttributeKey.valueOf("uploadMsg");
        Attribute<String> attr = ctx.channel().attr(attKey);

        AttributeKey<String> argKey = AttributeKey.valueOf("arg");
        Attribute<String> argAttr = ctx.channel().attr(argKey);

        String arg = argAttr.get();
        if(null == arg || arg.equals("")){
            getDispose().dispose(attr.get(),null, type);
        }else{
            //重传数据保存到手动处理目录下，并保持原有路径
            getDispose().dispose(attr.get(), arg, ExceptionType.MANUAL_ERROR);
        }
    }
}
